package com.sunlee.app.api.controller;


import com.sunlee.app.api.annotation.Login;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.validator.ValidatorUtils;
import com.sunlee.common.service.enums.StatusEnum;
import com.sunlee.app.api.entity.dto.LoginDTO;
import com.sunlee.app.api.entity.dto.RegisterDTO;
import com.sunlee.common.service.entity.CommonUserEntity;
import com.sunlee.app.api.entity.dto.WxMpLoginDTO;
import com.sunlee.app.api.entity.vo.UserInfoVO;
import com.sunlee.app.api.service.TokenService;
import com.sunlee.app.api.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Map;

/**
 * 登录接口
 *
 * @author sunlee
 */
@RestController
@RequestMapping("/user")
public class ApiLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("login")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        //用户登录
        Map<String, Object> map = userService.login(dto);
        return Result.ok(map);
    }

    @PostMapping("wxMpLogin")
    public Result<UserInfoVO> wxMpLogin(@Validated @RequestBody WxMpLoginDTO dto) {
        UserInfoVO userInfoVO = userService.wxMpLogin(dto);
        return Result.ok(userInfoVO);
    }

    @Login
    @PostMapping("logout")
    public Result<Object> logout(@ApiIgnore @RequestHeader String token) {
        tokenService.expireToken(token);
        return Result.ok();
    }

    @PostMapping("register")
    public Result<Object> register(@RequestBody RegisterDTO dto){
        //表单校验
        ValidatorUtils.validateEntity(dto);

        CommonUserEntity user = new CommonUserEntity();
        user.setMobile(dto.getMobile());
        user.setUsername(dto.getMobile());
        user.setPassword(DigestUtils.sha256Hex(dto.getPassword()));
        user.setCreateDate(new Date());
        user.setStatus(StatusEnum.VALID.getCode());
        userService.insertOwn(user);

        return Result.ok();
    }
}